package com.momo.demo.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;

/**
 * 模仿调用接口次数，现实使用次数的 一种小案例
 */
public class Service {
    /*
    * 模仿用户id
    * */
    private String val;

    /*
    *  限制次数
    * */
    private int num;

    /**
     *
     * @param id 用户id
     * @param num 限制次数
     */
    public Service(String id,int num) {
        this.val = id;
        this.num = num;
    }

    public void service() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.auth("root");
        String s = jedis.get("compid:" + val);
        //判断该值是否窜在
        try {
            if (s == null) {
                //不存在 因为在redis中数值最大范围 9223372036854775807
                jedis.setex("compid:" + val, 5, Long.MAX_VALUE - num + "");
            } else {

                //存在 自增并且调用
                Long incr = jedis.incr("compid:" + val);
                business(s,num-(Long.MAX_VALUE - incr));//计算已经使用的次数
            }
        } catch (JedisDataException e) {
            System.out.println("使用次数达到上线，请升级会员级别");
            return;
        } finally {
            jedis.close();
        }
    }

    public void business(String id,Long val) {
        System.out.println(id + "===>" +val + "次数");
        System.out.println("业务操作执行");
    }

    static class MyThread extends Thread {
        Service sc;
        public MyThread ( String id ,int num){
            sc = new Service(id,num);
        }
        public void run() {
            while (true) {
                try {
                    Thread.sleep(300L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sc.service();
            }
        }
    }

    static class Main {
        public static void main(String[] args) {
            MyThread myThread1 = new MyThread("初级用户",10);
            MyThread myThread2 = new MyThread("高级用户",5);
            myThread1.start();
            myThread2.start();
        }
    }
}
